from option import Option
from twisted.spread import pb

CLOSED = 0
REG = REGISTRATION = 1
ONGOING = 32
PAUSED = 64
FINISHED = 255

class Event(pb.Viewable):

	def __init__(self, title, description = ''):
		self.title = title
		self.description = description
		self.phase = CLOSED

		self.competitors = []
		self.rounds = []
		self.current = None
		self.currentNum = 0

		self.preinspection = 'Stackmat'

	def start(self):
		assert not Option().currentEvent, 'Simultaneous events are not allowed'
		assert not self.phase == FINISHED and not self.phase == CLOSED, 'Event already finished or closed.'
		assert not self.phase == ONGOING, 'Event is active.'
		assert self.rounds, "Event's round schedule is incomplete."

		self.phase = ONGOING
		
		if self.currentNum == 0:
			self.current = self.rounds[0]

			self.current.competitors.extend(self.competitors)

		self.current.start()
		Option().currentEvent = self

		Option().log.info('Starting competiton %s, round %s.' % (self.title, self.current.title))
		Option().chat.send('sys', '%s: %s starting.' % (self.title, self.current.title))
	
	def finishRound(self):
		assert self.phase == ONGOING, 'Event is not active.'

		Option().log.info('%s: round %s finished.' %(self.title, self.current.title))
		Option().chat.send('sys', '%s: %s finished.' % (self.title, self.current.title))

		self.currentNum += 1

		if self.currentNum < len(self.rounds):
			old = self.current
			self.current = self.rounds[self.currentNum]

			self.current.competitors.extend(old.getAdvanced())

			self.phase = PAUSED
		else:
			Option().log.info('Competition %s finished.' % self.title)
			Option().chat.send('sys', '%s: Competition finished' % self.title)

			self.current = None

			self.phase = FINISHED

		
		Option().currentEvent = None
	
	def view_getInfo(self, avatar):
		return (self.title, self.description, self.phase, avatar in self.competitors)

	def view_currentRound(self, avatar):
		assert self.phase == ONGOING or self.phase == PAUSED, 'Event is finished or not started.'
		return self.current

